package com.cyj.springbootservice.utils;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * @description:
 * @Author C_Y_J
 * @create 2021/11/16 17:23
 **/
public class AliOssUtil {

    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId = "LTAI5tC4kUimY79LomHQJGgn";
    private static String accessKeySecret = "QdjGNHihirIFlwTXRsJDRrlmtHvUnz";
    private static String bucketName = "air-lxzn-v1";

    /**
     * @Description: 上传公开文件至公共读写bucket，返回文件存储的URL路径
     * @Param uploadFile 上传的文件
     * @Return: java.lang.String
     * @Author: 大佬味的小男孩 C_Y_J
     * @Date: 2021/11/16 17:25
     **/
    public static String uploadFile(MultipartFile uploadFile) throws Exception {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // key：自动规则 + uploadFile.getOriginalFilename()
        String key = "upload/" + DateUtil.now() + "/" + uploadFile.getOriginalFilename();
        ossClient.putObject(bucketName, key, new ByteArrayInputStream(uploadFile.getBytes()));
        // 关闭client
        ossClient.shutdown();

        // 设置过期时间 十年
/*      Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        return ossClient.generatePresignedUrl(bucketName, key, expiration).toString();*/

        return fileLink(endpoint, bucketName, key);
    }

    /**
     * 因为阿里云只提供预防问链接（？后面带参数），对保存URL路径很不友好
     * 所以根据 endpoint bucketName key 手动拼接
     *
     * @param endpoint
     * @param bucketName
     * @param key
     * @return
     */
    public static String fileLink(String endpoint, String bucketName, String key) {
        String prefix = endpoint.contains("https://") ? "https://" : "http://";
        String URL = prefix + bucketName + "." + endpoint.replaceFirst(prefix, "");
        return URL.concat("/").concat(key);
    }

}



